var app = angular.module('breadTrip', []);
// 解决jinja2和angular的花括号{{}}冲突的方法
app.config(['$interpolateProvider', function($interpolateProvider) {
    $interpolateProvider.startSymbol('{[');
    $interpolateProvider.endSymbol(']}');
}]);
app.controller('hotelController', ['$scope', function($scope){
    $scope.data = {
        'checkin_date' : BT.context('checkin_date'),
        'checkout_date' : BT.context('checkout_date'),
        'rooms_count' : BT.context('rooms_count'),
        'today' : moment().format('l')
    };
    $scope.data.products = obj;
    $scope.data.checkin_date = moment($scope.data.checkin_date)._d;
    $scope.data.checkout_date = moment($scope.data.checkout_date)._d;
    $scope.data.today = moment($scope.data.today)._d;

    $scope.objTostring = function(array){
        var new_array = [];
        array.filter(function(obj, k){
            for(var i in obj){
                if(i == 'name') new_array.push(obj[i]);   
            }
        });
        return new_array.join('/');
    };

    // top slider 
    function topSlider(){
        var $swiper = $('#swiper-container'),
            length = $swiper.data('length');
        if (length <= 1) {
            return false;
        }
        var slider = new Swiper('#swiper-container', {
            mode: 'horizontal',
            loop: true,
            autoplay: 3000,
            pagination: '.swiper-pagination',
            onTouchStart: function(){
                setTimeout(function(){
                    slider.startAutoplay();
                }, 3000);
            }
        });
        $scope.$watch("data", function(){}, true);
    }
    function getRooms(){
        var url = location.origin + '/hotel/product/list/search/'+ BT.context('hotel_id') +'/?checkin_date='+
            moment($scope.data.checkin_date).format('l') + '&checkout_date=' + 
            moment($scope.data.checkout_date).format('l') + '&rooms_count=' + $scope.data.rooms_count;
        $.ajax({
            url: url,
            type: "GET",
            success: function(resp){
                if(resp){
                    $scope.data.products = JSON.parse(resp);
                    $scope.$apply(); //强制通知
                    $('input').blur();
                }
            },
            error: function(resp) {
                $scope.data.products = [];
                $scope.$apply(); //强制通知
                // alert('对不起，网络错误！');
            }
        });
    }

    if($scope.data.outer) $('#checkoutDate').prop('value',  moment($scope.data.chechin_date).add(1, 'days')._d);

    $scope.changeIndate = function(){
        var $checkin_date = $('#checkinDate'),
            $checkout_date = $('#checkoutDate');
        if(moment($checkin_date.val()).isBefore($scope.data.today)){
            $scope.data.checkin_date = moment($scope.data.today)._d;
            $checkin_date.prop('value',  $scope.data.checkin_date);
        }else{
            if(moment($checkin_date.val()).isAfter($scope.data.checkout_date)) $scope.data.outer = true;
        }
        getRooms();
    };

    $scope.changeOutdate = function(type){
        var $checkin_date = $('#checkinDate'),
            $checkout_date = $('#checkoutDate');

        if(moment($checkout_date.val()).isBefore($scope.data.today)){
            if(moment($checkout_date.val()).isAfter($scope.data.checkin_date)){
                $scope.data.checkout_date = moment($scope.data.today)._d;
            }else{
                $scope.data.checkout_date = moment($scope.data.checkin_date).add(1, 'days')._d;  
            }
            $checkout_date.prop('value',$scope.data.checkout_date);
        }else{
            if(moment($checkout_date.val()).isAfter($scope.data.checkin_date)){
                if(Math.abs(moment($checkout_date.val()).diff($scope.data.checkin_date, "days")) > 30){
                    $scope.data.checkout_date = moment($scope.data.checkin_date).add(30, 'days')._d;
                    $checkout_date.prop('value',$scope.data.checkout_date);
                }
            }else{
                $scope.data.checkout_date = moment($scope.data.checkin_date).add(1, 'days')._d;
                $checkout_date.prop('value',$scope.data.checkout_date);
            }
        }
        getRooms();
    };

    $scope.selectRoom = function(n){
        $scope.data.rooms_count = n;
        getRooms();
    };
    $scope.goMap = function(lon, lat, title, address){
        var ua = navigator.userAgent.toLowerCase();
        lon = parseFloat(lon);
        lat = parseFloat(lat);
        if(ua.match(/MicroMessenger/i) == 'micromessenger'){
            wx.ready(function(){
                wx.openLocation({
                    latitude: lat,
                    longitude: lon,
                    name: title,
                    address: address,
                    scale: 12,
                    infoUrl: ''
                });
            });
        }else{
            var url = location.origin + '/hotel/map/?' + 'title=' + title + '&latitude=' + lat + '&longitude=' + lon + '&zoom=' + 12;
            location.href = url;
        }
    };
    $scope.blur = function($event){
        var $dom = $($event.target),
            ua = navigator.userAgent.toLowerCase(),
            _name = $dom.attr('name'),
            _val = $('input[name="' +_name+ '"]').val();

        $scope.data[_name] = _val;
        if(ua.indexOf('android') >= 0 && ua.indexOf('micromessenger') >= 0 ){
            getRooms();
        } 
    };
    $scope.goRoom  = function(id){
        location.href = location.origin + '/hotel/product/' + BT.context('hotel_id') 
            + '/?checkin_date=' + moment($scope.data.checkin_date).format('l')
            + '&checkout_date=' + moment($scope.data.checkout_date).format('l')
            + '&rooms_count=' + $scope.data.rooms_count
            + '&product_id=' + id;
    };
    $scope.goHref = function(href){
        location.href = href;
    };
    $scope.goBook = function(href){
        if($('#book-btn').hasClass('disabled')) return;
        location.href = location.origin + href 
            + '?checkin_date=' + moment($scope.data.checkin_date).format('l')
            + '&checkout_date=' + moment($scope.data.checkout_date).format('l')
            + '&rooms_count=' + $scope.data.rooms_count;
    };
    $scope.round = function(price){
        return Math.round(price);
    }
    topSlider();
}]);
app.directive("formatDate", function(){
  return {
   require: 'ngModel',
    link: function(scope, elem, attr, modelCtrl) {
      modelCtrl.$formatters.push(function(modelValue){
        return new Date(modelValue);
      })
    }
  }
});
$(function(){
    var friend = {
        title: shr_wechat_title_friend,
        desc: shr_wechat_summary_friend,
        link: location.href,
        imgUrl: shr_wechat_image
    };
    var friend_quan = {
        title: shr_wechat_title_circle,
        desc: shr_wechat_summary_circle,
        link: location.href,
        imgUrl: shr_wechat_image
    };
    wx.ready(function(){
        wx.onMenuShareAppMessage(friend);
        wx.onMenuShareTimeline(friend_quan);
    });
});